package com.hsy.crm.web.utils;

import com.hsy.crm.web.domain.ex.UtilsException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by admin on 2018/4/16.
 */
public class DateUtils {

    private DateUtils(){}

    private static final String PATTERN_SHORT = "yyyyMMdd";
    private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

    private static final ThreadLocal<DateFormat> SDF_LOCAL_SHORT = getLocalFormat(PATTERN_SHORT);
    private static final ThreadLocal<DateFormat> SDF_LOCAL = getLocalFormat(PATTERN);


    public static ThreadLocal<DateFormat> getLocalFormat(final String format){
        return ThreadLocal.withInitial(() -> new SimpleDateFormat(format));
    }


    public static Date now(){
        return new Date();
    }

    public static String format(Date date){
        return format(date,SDF_LOCAL);
    }

    public static String format(Date date,String format){
        return format(date,getLocalFormat(format));
    }

    public static String formatShort(Date date){
        return SDF_LOCAL_SHORT.get().format(date);
    }

    public static Date parse(String date){
        try {
            return SDF_LOCAL.get().parse(date);
        } catch (ParseException e) {
            throw new UtilsException(e);
        }
    }

    public static Date parseShort(String date){
        try {
            return SDF_LOCAL_SHORT.get().parse(date);
        } catch (ParseException e) {
            throw new UtilsException(e);
        }
    }

    public static long millis(){
        return System.currentTimeMillis();
    }

    private static String format(Date date,ThreadLocal<DateFormat> sdf){
        return sdf.get().format(date);
    }

}
